/*
 * serialTest.c:
 *	Very simple program to test the serial port. Expects
 *	the port to be looped back to itself
 *
 * Copyright (c) 2012-2013 Gordon Henderson. <projects@drogon.net>
 ***********************************************************************
 * This file is part of wiringPi:
 *	https://projects.drogon.net/raspberry-pi/wiringpi/
 *
 *    wiringPi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    wiringPi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with wiringPi.  If not, see <http://www.gnu.org/licenses/>.
 ***********************************************************************
 */

#include <stdio.h>
#include <string.h>
#include <errno.h>

#include <wiringPi.h>
#include <wiringSerial.h>

int main ()
{
  int fd ;
  

  if ((fd = serialOpen ("/dev/ttyUSB0", 38400)) < 0)
  {
    fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
    return 1 ;
  }

  if (wiringPiSetup () == -1)
  {
    fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
    return 1 ;
  }


	char *zig1 = "u";
	char response[100];
	int i = 0;
	int dist;
      fflush (stdout) ;
    while (1){
	serialPuts(fd, zig1);
	serialPutchar(fd, 13);
	printf("\n%s\n", zig1);
    //delay (500) ;
	//printf("\ndelay");
    while (serialDataAvail (fd))
    {
      //sprintf ("%c", serialGetchar (fd)) ;
	response[i++] = serialGetchar(fd);
      fflush (stdout) ;
    }
    delay(1000);
    if (strncmp(response, "Sharp value = ", 13) == 0){
     	printf("\n->%s\n", response);
        sscanf(response, "%*s %*s %*s %d", &dist);
  	printf("= %d\n", dist);
    }
    else
	printf("\nNope, ni goed\n");
    i =0;
    memset(response,0, strlen(response));
    }

  printf ("\n") ;
  return 0 ;
}
